package com.jt.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.User;
import com.jt.service.DubboUserService;
import com.jt.vo.SysResult;

import redis.clients.jedis.JedisCluster;


@Controller
@RequestMapping("/user")
public class UserController {
	/**
	 * 用户登录和注册页面的跳转
	 * http://www.jt.com/user/login.html-->/user/login
	 * http://www.jt.com/user/register.html-->/user/register
	 */
	@RequestMapping("/{moduleName}")
	public String loginAndRegister(@PathVariable String moduleName) {
		return moduleName;
	}
	
	@Reference(timeout = 3000, check = false)
	private DubboUserService dubboUserService;//消费者调用dubbo框架接口
	@Autowired
	private JedisCluster jedisCluster;
	
	/**
	 * 实现用户注册
	 */
	@RequestMapping("/doRegister")
	@ResponseBody
	public SysResult insertUser(User user) {
		dubboUserService.insertUser(user);
		return SysResult.success();
	}
	
	/**
	 * 用户登录
	 * url http://www.jt.com/user/doLogin
	 * username: admin1904
     * password: admin123
	 */
	@RequestMapping("/doLogin")
	@ResponseBody
	public SysResult doLogin(User user,HttpServletResponse response) {
		//1.获取加密密钥
		String ticket=dubboUserService.doLogin(user);
		if (StringUtils.isEmpty(ticket)) {
			return SysResult.fail();
		}
		//2.将数据保存到cookie中
		Cookie cookie=new Cookie("JT_TICKET", ticket);
		cookie.setMaxAge(7*24*3600);//设置cookie存活时间
		cookie.setPath("/");//设置cookie的使用权限
		cookie.setDomain("jt.com");//设置cookie在jt.com总项目下共享
		response.addCookie(cookie);//将cookie写入浏览器
		return SysResult.success();
	}
	
	/**
	 * 用户退出
	 * url http://www.jt.com/user/logout.html
	 * 1.删除redis 
	 * 2.删除cookie
	 * 3.重定向到首页
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response) {
		//1.获取浏览器的cookie数据
		Cookie[] cookies = request.getCookies();
		//2.判断cookie是否有值
		String ticket=null;
		if (cookies.length>0) {
			for (Cookie cookie : cookies) {
				if ("JT_TICKET".equals(cookie.getName())) {
					ticket=cookie.getValue();
					break;
				}
			}
		}
		//3.删除redis
		if (!StringUtils.isEmpty(ticket)) {
			jedisCluster.del(ticket);
		}
		//4.删除cookie（cookie本身没有删除操作，可以通过新建cookie覆盖）
		Cookie cookie=new Cookie("JT_TICKET", "");//不要设置为null，防止有些浏览器不支持
		cookie.setMaxAge(0);// >0表示设置存货时间，=0表示立即删除，-1表示等回话结束后删除
		cookie.setPath("/");
		cookie.setDomain("jt.com");
		response.addCookie(cookie);
		//5.重定向到首页 index.jsp
		return "redirect:/";
	}
	
}
